package com.linkcard.list.persistence;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.linkcard.commen.tools.Page;
import com.linkcard.list.model.Feedback;

public class FeedbackDaoImpl extends HibernateDaoSupport implements FeedbackDao {

	//添加留言
	public boolean addFeedback(Feedback feedback) {
		try
		{
			this.getHibernateTemplate().save(feedback);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//获得留言
	public List feedbackList(final Page pageObj) {
		List list=(List)this.getHibernateTemplate().execute(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria criteria=session.createCriteria(Feedback.class);
				         int rowCount=	(Integer)criteria.setProjection(Projections.count("id")).uniqueResult();
					     pageObj.setRowCount(rowCount);
			             pageObj.setTotalPage(rowCount);
			             
						 criteria.setProjection(null);
						 criteria.addOrder(Order.desc("datetime"));
						 criteria.setFirstResult((pageObj.getCurrentPage()-1)*pageObj.getPageSize());
						 criteria.setMaxResults(pageObj.getPageSize());
				return criteria.list();
			}
			
		});
		return list;
	}

	//删除留言
	public boolean deleteFeedback(Integer id) {
		try
		{
			Feedback f=(Feedback)this.getHibernateTemplate().get(Feedback.class, id);
			this.getHibernateTemplate().delete(f);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

	//修改留言
	public boolean modifyFeedback(Feedback feedback) {
		try
		{
			Feedback f=(Feedback)this.getHibernateTemplate().get(Feedback.class, feedback.getId());
			f.setReply(feedback.getReply());
			f.setReplyDatetime(feedback.getReplyDatetime());
			this.getHibernateTemplate().update(f);
		}catch(Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
